//
//  AppDelegate.m
//  HKTimeKitApp
//
//  Created by huzhaoke1 on 2023/5/8.
//

#import "AppDelegate.h"
#import "HKUser.h"
#import "UIView+HKSafeArea.h"
#import "UIImage+color.h"
#import "HKLoginController.h"
#import "HKShareWebViewControllerManager.h"
//#import <AVFoundation/DFAVSpeechManager.h>
#import "HKUITool.h"
#import "HTTPURL.h"
#import <AudioToolbox/AudioToolbox.h>
@interface AppDelegate () <JPUSHRegisterDelegate>
@property (nonatomic,strong) NSDictionary *remoteNotification;
@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, assign) BOOL isBackGroundRunning;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [HKShareWebViewControllerManager sharedInstance];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    [self initAppRootVC];
    if(self.remoteNotification){
        NSString *url = self.remoteNotification[@"jpush_pri_rich_url"];
        NSString *index = self.remoteNotification[@"category"];
        if (!index){
            HKWebViewController *webViewController = [HKWebViewController new];
            [webViewController loadingRequestWithUrl:url];
            [[HKUITool getCurrentNavgationController]pushViewController:webViewController animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self initPush:launchOptions];
            });
        }
     }else{
        [self initPush:launchOptions];
    }
    
    WKWebView *wkWebView = [WKWebView new];
    [self.window addSubview:wkWebView];
    [wkWebView removeFromSuperview];
    
    return YES;
}

- (void)initPush:(NSDictionary *)launchOptions {
    //【注册通知】通知回调代理（可选）
     JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
     entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings|JPAuthorizationOptionSound;
     [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions
                           appKey:@"30695e6f1de8bb29d773b0fb"
                          channel:@""
                 apsForProduction:NO
            advertisingIdentifier:@""];
    [self jpRegisterObserver];
    HKUser *user = WMglobalUser();
    if (user) {
        [JPUSHService setAlias:[NSString stringWithFormat:@"%@_alias", user.phone] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            if (iResCode == 0) {
                NSLog(@"添加别名成功");
            }
        } seq:1];
    }
}

+ (AppDelegate *)appDelegate {
    return KSSAFE_CAST([UIApplication sharedApplication].delegate, AppDelegate);
}

-(void)initAppRootVC {
    HKUser *user = WMglobalUser();
    if (user) {
        [self createMainController]; // 已经登录的页面
    } else {
        [self createLoginController];// 需要登录的页面
    }
}

-(void)createMainController {
    self.mainTabBarViewController = [HKRootTabBarViewController new];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:self.mainTabBarViewController];
    self.keyNavi = navi;
    self.window.rootViewController = navi;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self setupTabbarIndicatorImageWithVC:self.mainTabBarViewController];
    });
    
}

- (void)createLoginController {
    HKLoginController *loginController = [HKLoginController new];
    self.window.rootViewController = loginController;
}

// privateMethod
- (void)setupTabbarIndicatorImageWithVC:(HKRootTabBarViewController *)vc {
    CGSize ctxSize = CGSizeMake(self.window.bounds.size.width / vc.tabBar.items.count, vc.tabBar.bounds.size.height);
    CGFloat bottom = self.window.safeAreaInsets.bottom;
    CGSize imageSize = CGSizeMake(76, 40);
    CGFloat imageTop = (ctxSize.height - bottom - imageSize.height) / 2;
    CGFloat imageLeft = (ctxSize.width - imageSize.width) / 2;
   
    CGRect rect = CGRectMake(imageLeft, imageTop, imageSize.width, imageSize.height);
    vc.tabBar.selectionIndicatorImage = [UIImage imageWithCtxSize:ctxSize imageRect:rect color:UIColorFromRGB(0xf8f9ff) corners:UIRectCornerAllCorners cornerRadius:5];
}

#pragma mark- JPUSHRegisterDelegate
- (void)jpRegisterObserver {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    self.isBackGroundRunning = YES;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [UIApplication sharedApplication].applicationIconBadgeNumber = -1;
    self.isBackGroundRunning = NO;
}

//与极光服务端建立长连接
- (void)networkDidSetup:(NSNotification *)notification {
     NSLog(@"极光推送已连接");
}

//长连接关闭
- (void)networkDidClose:(NSNotification *)notification {
     NSLog(@"极光推送未连接。。。");
}

//注册成功
- (void)networkDidRegister:(NSNotification *)notification {
     NSLog(@"极光推送已注册");
}

- (void)application:(UIApplication *)application
    didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
}


//登录成功
- (void)networkDidLogin:(NSNotification *)notification {
     NSLog(@"极光推送已登录");
}
- (NSString *)logDic:(NSDictionary *)dic {
  if (![dic count]) {
    return nil;
  }
  NSString *tempStr1 =
      [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                   withString:@"\\U"];
  NSString *tempStr2 =
      [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
  NSString *tempStr3 =
      [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
  NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
  NSString *str =
      [NSPropertyListSerialization propertyListFromData:tempData
                                       mutabilityOption:NSPropertyListImmutable
                                                 format:NULL
                                       errorDescription:NULL];
  return str;
}

//设置消息送达代理
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler {

    [self openVibrate];
    
    NSDictionary *userInfo = notification.request.content.userInfo;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Incoming" object:nil userInfo:userInfo];

    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置

    NSDictionary * contentUserInfo = notification.request.content.userInfo;

    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    NSString *url = contentUserInfo[@"jpush_pri_rich_url"];
    NSLog(@"%@",url);
//    HKWebViewController *webViewController = [HKWebViewController new];
//    [webViewController loadingRequestWithUrl:url];
//    [[HKUITool getCurrentNavgationController]pushViewController:webViewController animated:YES];

    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 收到远程通知:%@", [self logDic:contentUserInfo]);

    } else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
}

/*
 * @brief handle UserNotifications.framework [didReceiveNotificationResponse:withCompletionHandler:]
 * @param center [UNUserNotificationCenter currentNotificationCenter] 新特性用户通知中心
 * @param response 通知响应对象
 * @param completionHandler
 */
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
    if (self.isBackGroundRunning){
        [self openVibrate];
    }    
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    NSString *index = userInfo[@"category"];
    if (index){
        completionHandler();  // 系统要求执行这个方法
        return;
    }
    NSString *url = userInfo[@"jpush_pri_rich_url"];
    HKWebViewController *webViewController = [HKWebViewController new];
    [webViewController loadingRequestWithUrl:url];
    [[HKUITool getCurrentNavgationController]pushViewController:webViewController animated:YES];

    completionHandler();  // 系统要求执行这个方法
}

- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(nullable NSDictionary *)info {
     
}


- (void)jpushNotificationCenter:(nonnull UNUserNotificationCenter *)center openSettingsForNotification:(nonnull UNNotification *)notification {
     
}

- (void)openVibrate {
    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, soundCompleteCallback, NULL);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
    __block NSInteger time = 3;
    self.queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
    dispatch_source_set_timer(self.timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(self.timer, ^{
         if(time <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
                AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                time--;
                NSLog(@"%ld",(long)time);
             });
        }
    });
    dispatch_resume(self.timer);
}

void soundCompleteCallback(SystemSoundID sound, void *clientDate) {
    if (sound == kSystemSoundID_Vibrate) {
        AudioServicesPlayAlertSound(sound); // 重复响铃震动
    } else {
        AudioServicesDisposeSystemSoundID(sound);
        AudioServicesRemoveSystemSoundCompletion(sound);
        
        AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
        AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
     }
}

@end

 
